package com.poetize.plus.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Optional;

/**
 * @author zuosy
 * @created 2024/3/28 19:20
 */
public class LoginUtils {

    /**
     * 获取当前登录人名称
     * @return
     */
    public static String getLoginUserName(){
        return Optional.ofNullable(getLoginUser()).map(User::getUsername).orElse(null);
    }

    /**
     * 获取当前登录人
     * @return
     */
    public static User getLoginUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Optional.ofNullable(authentication).map(au -> (User) au.getPrincipal()).orElse(null);
    }

    /**
     * 密码初始化
     * @param args
     */
    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode("123456");
        System.out.println("password = " + password);
    }
}
